package com.leizi.igym.service.impl;

import java.time.LocalDate;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leizi.igym.BaseContext.UserThreadLocal;
import com.leizi.igym.constant.EmployeeConstant;
import com.leizi.igym.domain.Employee;
import com.leizi.igym.dto.EmployeeAddDTO;
import com.leizi.igym.dto.EmployeePageQueryDTO;
import com.leizi.igym.enums.ReturnCodeEnum;
import com.leizi.igym.exception.BusinessException;
import com.leizi.igym.mapper.EmployeeMapper;
import com.leizi.igym.mapper.UserMapper;
import com.leizi.igym.pojo.ContextUser;
import com.leizi.igym.service.EmployeeService;
import com.leizi.igym.utils.DateQWUtils;
import com.leizi.igym.utils.ThrowUtils;
import com.leizi.igym.vo.EmployeeVO;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author PC
 * @description 针对表【t_employee(员工表)】的数据库操作Service实现
 * @createDate 2024-04-03 14:28:34
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee>
        implements EmployeeService {

    @Resource
    private UserMapper userMapper;

    /**
     * 获取员工分页查询条件构造器
     *
     * @param employeePageQueryDTO
     * @return: QueryWrapper<com.leizi.igym.domain.Employee>
     **/
    @Override
    public QueryWrapper<Employee> getQueryWrapper(EmployeePageQueryDTO employeePageQueryDTO) {
        ThrowUtils.throwIf(Objects.isNull(employeePageQueryDTO), ReturnCodeEnum.PARAMS_ERROR);

        //  获取分页查询参数
        String empName = employeePageQueryDTO.getEmpName();
        Integer isIdentify = employeePageQueryDTO.getIsIdentify();
        LocalDate beginTime = employeePageQueryDTO.getBeginTime();
        LocalDate endTime = employeePageQueryDTO.getEndTime();
        String phone = employeePageQueryDTO.getPhone();
        Long id = employeePageQueryDTO.getId();

        //  根据参数构造queryWrapper
        QueryWrapper<Employee> qw = new QueryWrapper<>();

        // 判断认证字段的合法性
        if (isIdentify != null) {
            ThrowUtils.throwIf(!EmployeeConstant.EMP_IDENTIFY_LIST.contains(isIdentify),
                    ReturnCodeEnum.PARAMS_ERROR);
            qw.eq("isIdentify", isIdentify);
        }

        // 判断时间的合法性
        // if (ObjectUtils.allNotNull(beginTime, endTime) && endTime.isAfter(beginTime)) {
        //     ThrowUtils.throwIf(!endTime.isAfter(beginTime), ReturnCodeEnum.PARAMS_ERROR, "传入的日期有误！");
        // }
        // if (Objects.nonNull(beginTime)) {
        //     qw.ge("create_time", LocalDateTime.of(beginTime, LocalTime.MIN));
        // }
        // if (Objects.nonNull(endTime)) {
        //     qw.le("create_time", LocalDateTime.of(endTime, LocalTime.MAX));
        // }
        DateQWUtils.getDateQWForEmp(qw, beginTime, endTime);

        qw.like(Objects.nonNull(id),"id",id);
        qw.like(!StringUtils.isBlank(empName), "emp_Name", empName);
        qw.like(!StringUtils.isBlank(phone), "phone", phone);
        qw.orderByDesc("isIdentify");
        qw.orderByDesc("update_time");

        return qw;
    }

    /**
     * 获取员工视图对象
     *
     * @param employee
     * @return: com.leizi.igym.vo.EmployeeVO
     **/
    @Override
    public EmployeeVO getEmployeeVO(Employee employee) {
        ThrowUtils.throwIf(ObjectUtils.isEmpty(employee), ReturnCodeEnum.PARAMS_ERROR);
        EmployeeVO employeeVO = new EmployeeVO();
        BeanUtils.copyProperties(employee, employeeVO);
        return employeeVO;
    }

    /**
     * 转化得到员工视图对象列表
     *
     * @param taskPage
     * @return: java.util.List<com.leizi.igym.vo.EmployeeVO>
     **/
    @Override
    public List<EmployeeVO> getEmployeeVOPage(Page<Employee> taskPage) {
        ThrowUtils.throwIf(ObjectUtils.isEmpty(taskPage), ReturnCodeEnum.PARAMS_ERROR);
        List<Employee> employeeList = taskPage.getRecords();
        List<EmployeeVO> employeeVOList = employeeList.stream().map(employee -> {
            EmployeeVO employeeVO = new EmployeeVO();
            BeanUtils.copyProperties(employee, employeeVO);
            return employeeVO;
        }).collect(Collectors.toList());
        return employeeVOList;
    }

    /**
     * 批量删除emp
     *
     * @param: [ids]
     * @return: boolean
     **/
    @Override
    public boolean removeEmpBatch(List<Long> ids) {
        // 校验id
        if (ids == null || ids.size() == 0) {
            throw new BusinessException(ReturnCodeEnum.PARAMS_ERROR, "id列表为空，无法删除");
        }
        // 判断用户是否存在
        for (Long id : ids) {
            if (getById(id) == null) {
                throw new BusinessException(ReturnCodeEnum.PARAMS_ERROR, "存在非法员工，无法删除");
            }
        }

        if (!removeBatchByIds(ids)) {
            throw new BusinessException(ReturnCodeEnum.SYSTEM_ERROR);
        }

        return true;
    }

    /**
     * 根据id查询emp
     *
     * @param: [id]
     * @return: com.leizi.igym.vo.EmployeeVO
     **/
    @Override
    public EmployeeVO getEmpById(Long id) {
        ThrowUtils.throwIf(Objects.isNull(id) || id < 0, ReturnCodeEnum.PARAMS_ERROR);
        Employee dbEmp = this.getBaseMapper().selectById(id);
        ThrowUtils.throwIf(Objects.isNull(dbEmp), ReturnCodeEnum.SYSTEM_ERROR);
        EmployeeVO employeeVO = new EmployeeVO();
        BeanUtils.copyProperties(dbEmp, employeeVO);
        return employeeVO;
    }

    /**
     * 对员工进行认证
     *
     * @param: [isIdentify]
     * @return: boolean
     **/
    @Override
    public boolean identifyEMp(Long id, Integer isIdentify) {
        // 校验参数id是否合法
        ThrowUtils.throwIf(Objects.isNull(id) || id < 0, ReturnCodeEnum.PARAMS_ERROR);
        // 校验isIdentify参数是否合法
        ThrowUtils.throwIf(Objects.isNull(isIdentify) ||
                !Arrays.asList(EmployeeConstant.NOT_IDENTIFY, EmployeeConstant.IDENTIFIED)
                        .contains(isIdentify), ReturnCodeEnum.PARAMS_ERROR);

        Employee dbEmp = this.getBaseMapper().selectById(id);
        ThrowUtils.throwIf(Objects.isNull(dbEmp), ReturnCodeEnum.PARAMS_ERROR);
        ThrowUtils.throwIf(dbEmp.getIsIdentify() == 1, ReturnCodeEnum.IDENTIFY_ERROR);
        dbEmp.setIsIdentify(isIdentify);
        dbEmp.setJoinTime(LocalDate.now());
        return this.getBaseMapper().updateById(dbEmp) > 0;
    }

    /**
     * 用户端认证成为员工
     *
     * @param dto
     * @return: long
     **/
    @Override
    public long addEmp(EmployeeAddDTO dto) {
        ThrowUtils.throwIf(Objects.isNull(dto), ReturnCodeEnum.PARAMS_ERROR);
        Employee employee = new Employee();
        BeanUtils.copyProperties(dto, employee);

        // 获取当前登录的用户对象
        ContextUser contextUser = UserThreadLocal.get();
        Long userId = contextUser.getId();
        // 查询数据库保证员工有且仅能够对应一个用户
        QueryWrapper<Employee> qw = new QueryWrapper<>();
        qw.eq(Objects.nonNull(userId), "user_id", userId);
        Long count = this.getBaseMapper().selectCount(qw);
        ThrowUtils.throwIf(count > 0, ReturnCodeEnum.EMP_EXIST_ERROR);

        // 插入新的员工数据
        employee.setUserId(userId);
        int i = this.getBaseMapper().insert(employee);
        return i > 0 ? employee.getId() : -1;
    }

    /**
     * 管理端修改员工消息
     *
     * @param employee
     * @return: boolean
     **/
    @Override
    public boolean updateEmpInAdmin(Employee employee) {
        ThrowUtils.throwIf(Objects.isNull(employee), ReturnCodeEnum.PARAMS_ERROR);
        String empName = employee.getEmpName();
        String avatar = employee.getAvatar();
        LocalDate birthday = employee.getBirthday();
        Integer gender = employee.getGender();
        String idNo = employee.getIdNo();
        String phone = employee.getPhone();
        Integer isIdentify = employee.getIsIdentify();

        // todo 参数合法性校验
        // 参数非空校验
        if (StringUtils.isAnyBlank(empName, avatar, idNo, phone)) {
            throw new BusinessException(ReturnCodeEnum.PARAMS_ERROR);
        }

        if (birthday == null) {
            throw new BusinessException(ReturnCodeEnum.PARAMS_ERROR);
        }

        if (!EmployeeConstant.EMP_IDENTIFY_LIST.contains(isIdentify) ||
                !EmployeeConstant.GENDER_LIST.contains(gender)) {
            throw new BusinessException(ReturnCodeEnum.PARAMS_ERROR);
        }

        // 插入消息
        Integer result = this.getBaseMapper().updateById(employee);
        return null != result && result >= 1;
    }

}




